<script setup>
import { ref } from "vue";
import ChannelSelect from "./ChannelSelect.vue";
import { Plus } from "@element-plus/icons-vue";
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  articlePublish,
  getArticleDetailService,
  updateArticleService,
} from "@/api/article";
import { ElMessage } from "element-plus";
import { urlToFile } from "@/utils/picToFile";

const imageUrl = ref("");
const emit = defineEmits(["success"]);
const isOpenDrawer = ref(false);
const formData = ref({
  title: "",
  cate_id: "",
  cover_img: null,
  content: "",
  state: "",
});

const open = async ({ id }) => {
  isOpenDrawer.value = true;
  if (id) {
    const {
      data: { data },
    } = await getArticleDetailService(id);
    formData.value = data;
    imageUrl.value = "http://big-event-vue-api-t.itheima.net" + data.cover_img;
    const file = await urlToFile(imageUrl.value, data.cover_img);
    formData.value.cover_img = file;
  }
};
const handleChange = (obj) => {
  const url = URL.createObjectURL(obj.raw);
  imageUrl.value = url;
  formData.value.cover_img = obj.raw;
};
const closeDrawer = () => {
  formData.value = {
    title: "",
    cate_id: "",
    cover_img: "",
    content: "",
    state: "",
  };
  imageUrl.value = "";
};
const onPublish = async (str) => {
  formData.value.state = str;
  const fd = new FormData();
  for (let key in formData.value) {
    fd.append(key, formData.value[key]);
  }
  if (!formData.value.id) {
    await articlePublish(fd);
    ElMessage.success("发布成功！");
    emit("success", "add");
  } else {
    await updateArticleService(fd);
    ElMessage.success("更新成功！");
    emit("success", "update");
  }
  formData.value = {
    title: "",
    cate_id: "",
    cover_img: "",
    content: "",
    state: "",
  };
  imageUrl.value = "";
  isOpenDrawer.value = false;
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const mode = ref("default");

defineExpose({
  open,
});
</script>

<template>
  <el-drawer
    v-model="isOpenDrawer"
    title="添加文章"
    size="40%"
    @close="closeDrawer"
  >
    <el-form style="padding: 0 20px" label-width="70px">
      <el-form-item label="文章标题">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <ChannelSelect v-model="formData.cate_id"></ChannelSelect>
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 200px; overflow-y: hidden"
            v-model="formData.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
